import React, { useState, useEffect, useCallback } from 'react';
import {
  Card,
  Row,
  Col,
  Statistic,
  Progress,
  Tag,
  Button,
  Typography,
  Space,
  Badge,
  notification,
  Spin,
  Tooltip,
  List,
  Avatar
} from 'antd';
import {
  UserOutlined,
  ShoppingCartOutlined,
  MessageOutlined,
  GlobalOutlined,
  DatabaseOutlined,
  WifiOutlined,
  PlayCircleOutlined,
  PauseCircleOutlined,
  SyncOutlined,
  WarningOutlined,
  CheckCircleOutlined,
  DollarOutlined,
  RobotOutlined,
  EnvironmentOutlined
} from '@ant-design/icons';
import * as dashboardService from '@/services/dashboard';
import type { AppStats, ChinaMapData, DeepSeekInfo } from '@/services/dashboard';
import type { ServerInfo, WebSocketMessage } from '@/types';
import {
  connectWebSocket,
  disconnectWebSocket,
  subscribeToMessages,
  isWebSocketConnected
} from '@/services/websocket';
import ChinaMap from '@/components/ChinaMap';

const { Title, Text } = Typography;

// 格式化字节数
const formatBytes = (bytes: number): string => {
  if (bytes === 0) return '0 B';
  const k = 1024;
  const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + ' ' + sizes[i];
};

// 格式化数字
const formatNumber = (num: number): string => {
  if (num >= 1000000) return (num / 1000000).toFixed(1) + 'M';
  if (num >= 1000) return (num / 1000).toFixed(1) + 'K';
  return num.toString();
};

// 格式化金额
const formatCurrency = (amount: number): string => {
  return new Intl.NumberFormat('zh-CN', {
    style: 'currency',
    currency: 'CNY',
    maximumFractionDigits: 0
  }).format(amount);
};

const Dashboard: React.FC = () => {
  const [appStats, setAppStats] = useState<AppStats | null>(null);
  const [serverInfo, setServerInfo] = useState<ServerInfo | null>(null);
  const [deepSeekInfo, setDeepSeekInfo] = useState<DeepSeekInfo | null>(null);
  const [wsConnected, setWsConnected] = useState(false);
  const [monitoring, setMonitoring] = useState(false);
  const [loading, setLoading] = useState(true);

  // 地图相关状态
  const [mapLevel, setMapLevel] = useState<'province' | 'city'>('province');
  const [mapData, setMapData] = useState<ChinaMapData | null>(null);

  // 加载地图数据
  const loadMapData = useCallback(async (level: 'province' | 'city') => {
    try {
      const data = await dashboardService.getChinaMapData({
        timeRange: 30,
        level: level,
        minVisits: 1
      });
      setMapData(data);
    } catch (error) {
      console.error('获取地图数据失败:', error);
    }
  }, []);

  // 加载所有数据
  const loadAllData = useCallback(async () => {
    try {
      const [stats, serverInfo, deepSeek] = await Promise.all([
        dashboardService.getAppStats(30),
        dashboardService.getServerInfo(),
        dashboardService.getDeepSeekInfo().catch(() => null) // DeepSeek可能不可用
      ]);

      setAppStats(stats);
      setServerInfo(serverInfo);
      setDeepSeekInfo(deepSeek);
    } catch (error: any) {
      console.error('获取数据失败:', error);
      notification.error({
        message: '数据加载失败',
        description: error?.message || '请检查网络连接'
      });
    }
  }, []);

  // WebSocket消息处理
  const handleWebSocketMessage = useCallback((message: WebSocketMessage) => {
    switch (message.type) {
      case 'server_monitor_start':
        setMonitoring(true);
        setServerInfo(message.data.serverInfo);
        break;
      case 'server_monitor_update':
        setServerInfo(message.data.serverInfo);
        break;
      case 'server_monitor_stop':
        setMonitoring(false);
        break;
    }
  }, []);

  // 连接WebSocket
  const connectWS = useCallback(async () => {
    try {
      await connectWebSocket();
      setWsConnected(true);
      subscribeToMessages('server_monitor_start', handleWebSocketMessage);
      subscribeToMessages('server_monitor_update', handleWebSocketMessage);
      subscribeToMessages('server_monitor_stop', handleWebSocketMessage);
    } catch (error: any) {
      setWsConnected(false);
      console.error('WebSocket连接失败:', error);
    }
  }, [handleWebSocketMessage]);

  // 切换监控状态
  const toggleMonitoring = useCallback(async () => {
    if (!wsConnected) {
      await connectWS();
      return;
    }
    try {
      if (monitoring) {
        await dashboardService.stopServerMonitor();
      } else {
        await dashboardService.startServerMonitor();
      }
    } catch (error: any) {
      console.error('切换监控状态失败:', error);
    }
  }, [wsConnected, monitoring, connectWS]);

  // 初始化地图数据
  useEffect(() => {
    if (mapLevel) {
      loadMapData(mapLevel);
    }
  }, [loadMapData, mapLevel]);

  // 初始化
  useEffect(() => {
    const init = async () => {
      setLoading(true);
      await loadAllData();
      setWsConnected(isWebSocketConnected());
      setLoading(false);
    };
    init();
  }, [loadAllData]);

  if (loading) {
    return (
      <div className="flex items-center justify-center h-64">
        <Spin size="large" tip="正在加载数据..." />
      </div>
    );
  }

  // 检测异常IP（非中国地区）
  const abnormalIPs = (appStats?.ipGeoLocation?.overview?.total_unique_ips || 0) - (appStats?.ipGeoLocation?.overview?.located_ips || 0);
  const abnormalRate = appStats?.ipGeoLocation?.overview?.total_unique_ips
    ? ((abnormalIPs / appStats.ipGeoLocation.overview.total_unique_ips) * 100).toFixed(1)
    : '0';

  return (
    <div className="h-screen overflow-hidden p-4 space-y-3">
      {/* 顶部标题和控制栏 - 紧凑设计 */}
      <div className="flex items-center justify-between">
        <Title level={3} className="mb-0">智能仪表盘</Title>
        <Space size="small">
          <Badge status={wsConnected ? "success" : "error"} />
          <Button
            size="small"
            type={monitoring ? "default" : "primary"}
            icon={monitoring ? <PauseCircleOutlined /> : <PlayCircleOutlined />}
            onClick={toggleMonitoring}
          >
            {monitoring ? "停止" : "监控"}
          </Button>
          <Button size="small" icon={<SyncOutlined />} onClick={loadAllData}>刷新</Button>
        </Space>
      </div>

      {/* 核心指标卡片 - 第一行 */}
      <Row gutter={[8, 8]}>
        <Col span={6}>
          <Card size="small" className="text-center">
            <Statistic
              title="用户总数"
              value={appStats?.users?.total_users || 0}
              prefix={<UserOutlined className="text-blue-500" />}
              valueStyle={{ fontSize: '20px', color: '#1890ff' }}
              suffix={
                <div className="text-xs text-gray-500">
                  今日+{appStats?.users?.new_users_today || 0}
                </div>
              }
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card size="small" className="text-center">
            <Statistic
              title="订单收入"
              value={appStats?.orders?.total_revenue || 0}
              prefix={<DollarOutlined className="text-green-500" />}
              valueStyle={{ fontSize: '20px', color: '#52c41a' }}
              formatter={(value) => formatCurrency(Number(value))}
              suffix={
                <div className="text-xs text-gray-500">
                  成功率{appStats?.orders?.payment_success_rate || 0}%
                </div>
              }
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card size="small" className="text-center">
            <Statistic
              title="AI对话"
              value={appStats?.aiChat?.total_messages || 0}
              prefix={<RobotOutlined className="text-purple-500" />}
              valueStyle={{ fontSize: '20px', color: '#722ed1' }}
              suffix={
                <div className="text-xs text-gray-500">
                  用户{appStats?.aiChat?.active_chat_users || 0}
                </div>
              }
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card size="small" className="text-center">
            <Statistic
              title="异常IP"
              value={abnormalIPs}
              prefix={<WarningOutlined className="text-orange-500" />}
              valueStyle={{
                fontSize: '20px',
                color: Number(abnormalRate) > 10 ? '#ff4d4f' : '#fa8c16'
              }}
              suffix={
                <div className="text-xs text-gray-500">
                  占比{abnormalRate}%
                </div>
              }
            />
          </Card>
        </Col>
      </Row>

      {/* 主要内容区域 - 第二行 */}
      <Row gutter={[8, 8]} style={{ height: 'calc(100vh - 200px)' }}>
        {/* 左侧：IP登录可视化地图 */}
        <Col span={16}>
          <Card
            size="small"
            title={
              <div className="flex items-center justify-between">
                <div className="flex items-center space-x-2">
                  <EnvironmentOutlined className="text-blue-500" style={{ fontSize: '16px' }} />
                  <span style={{ fontSize: '14px', fontWeight: 600 }}>IP登录可视化</span>
                  <div className="h-4 w-px bg-gray-300"></div>
                  <Text type="secondary" style={{ fontSize: '12px' }}>
                    {formatNumber(mapData?.summary?.total_users || 0)}用户 | {formatNumber(mapData?.summary?.total_visits || 0)}次访问
                  </Text>
                </div>
                <div className="flex items-center space-x-2">
                  <Button.Group size="small">
                    <Button
                      type={mapLevel === 'province' ? 'primary' : 'default'}
                      onClick={() => {
                        setMapLevel('province');
                        loadMapData('province');
                      }}
                      style={{ fontSize: '11px', padding: '2px 12px', height: '24px' }}
                    >
                      省份级
                    </Button>
                    <Button
                      type={mapLevel === 'city' ? 'primary' : 'default'}
                      onClick={() => {
                        setMapLevel('city');
                        loadMapData('city');
                      }}
                      style={{ fontSize: '11px', padding: '2px 12px', height: '24px' }}
                    >
                      城市级
                    </Button>
                  </Button.Group>
                </div>
              </div>
            }
            className="h-full"
            bodyStyle={{ padding: '12px' }}
          >
            {mapData && mapData.mapData.length > 0 ? (
              <ChinaMap
                data={mapData}
                height={400}
                onProvinceClick={(province: string) => {
                  notification.info({
                    message: `${province}省IP分析`,
                    description: `查看${province}省的详细IP登录分布，点击切换到城市级别`,
                    duration: 3
                  });
                  // 切换到城市级别查看
                  setMapLevel('city');
                  loadMapData('city');
                }}
                onCityClick={(province: string, city: string) => {
                  notification.info({
                    message: `${province}-${city}IP详情`,
                    description: `${city}市的IP登录统计和地理分布分析`,
                    duration: 3
                  });
                }}
              />
            ) : (
              <div className="flex items-center justify-center bg-gradient-to-br from-blue-50 to-indigo-50 rounded-lg border border-blue-100" style={{ height: '400px' }}>
                <div className="text-center">
                  <div className="mb-4">
                    <GlobalOutlined style={{ fontSize: '64px', color: '#1890ff', opacity: 0.6 }} />
                  </div>
                  <div style={{ fontSize: '16px', color: '#666', marginBottom: '8px' }}>
                    正在加载IP登录分布数据...
                  </div>
                  <div style={{ fontSize: '12px', color: '#999' }}>
                    分析全国用户登录地理位置分布
                  </div>
                </div>
              </div>
            )}
          </Card>
        </Col>

        {/* 右侧：系统监控、热门地区和DeepSeek状态 */}
        <Col span={8}>
          <Row gutter={[8, 8]} className="h-full">
            {/* 系统监控 */}
            <Col span={12}>
              <Card
                size="small"
                title={
                  <div className="flex items-center justify-between">
                    <div className="flex items-center space-x-2">
                      <DatabaseOutlined className="text-green-500" style={{ fontSize: '14px' }} />
                      <span style={{ fontSize: '13px', fontWeight: 600 }}>系统监控</span>
                    </div>
                    {monitoring && <Badge status="processing" text="实时" />}
                  </div>
                }
                className="h-full"
                bodyStyle={{ padding: '10px' }}
              >
                {serverInfo && (
                  <div className="space-y-3">
                    <div>
                      <div className="flex justify-between text-xs mb-1">
                        <span>CPU使用率</span>
                        <span className="font-medium">{serverInfo.cpu.load.currentLoad.toFixed(1)}%</span>
                      </div>
                      <Progress
                        percent={Number(serverInfo.cpu.load.currentLoad.toFixed(1))}
                        size="small"
                        strokeColor={serverInfo.cpu.load.currentLoad > 80 ? "#ff4d4f" : "#52c41a"}
                      />
                    </div>

                    <div>
                      <div className="flex justify-between text-xs mb-1">
                        <span>内存使用率</span>
                        <span className="font-medium">{serverInfo.memory.usagePercent}%</span>
                      </div>
                      <Progress
                        percent={Number(serverInfo.memory.usagePercent)}
                        size="small"
                        strokeColor={Number(serverInfo.memory.usagePercent) > 80 ? "#ff4d4f" : "#1890ff"}
                      />
                      <div className="flex justify-between text-xs mt-1 text-gray-500">
                        <span>{formatBytes(serverInfo.memory.used)}</span>
                        <span>{formatBytes(serverInfo.memory.total)}</span>
                      </div>
                    </div>

                    <div className="grid grid-cols-2 gap-2 text-xs">
                      <div className="text-center p-2 bg-green-50 rounded border border-green-100">
                        <div className="font-medium text-green-600">{serverInfo.cpu.cores}</div>
                        <div className="text-gray-500">核心</div>
                      </div>
                      <div className="text-center p-2 bg-blue-50 rounded border border-blue-100">
                        <div className="font-medium text-blue-600">{formatBytes(serverInfo.memory.total)}</div>
                        <div className="text-gray-500">内存</div>
                      </div>
                    </div>

                    <div className="text-xs bg-gray-50 p-2 rounded">
                      <div className="flex justify-between mb-1">
                        <span>系统:</span>
                        <span className="font-medium">{serverInfo.distro}</span>
                      </div>
                      <div className="flex justify-between">
                        <span>运行:</span>
                        <span className="font-medium">{Math.floor(serverInfo.uptime / 3600)}h</span>
                      </div>
                    </div>
                  </div>
                )}
              </Card>
            </Col>

            {/* 热门地区 */}
            <Col span={12}>
              <Card
                size="small"
                title={
                  <div className="flex items-center space-x-2">
                    <GlobalOutlined className="text-orange-500" style={{ fontSize: '14px' }} />
                    <span style={{ fontSize: '13px', fontWeight: 600 }}>热门IP地区</span>
                  </div>
                }
                className="h-full"
                bodyStyle={{ padding: '10px' }}
              >
                <List
                  size="small"
                  dataSource={appStats?.ipGeoLocation?.provinces?.slice(0, 6) || []}
                  renderItem={(item, index) => (
                    <List.Item className="py-1 px-0">
                      <div className="flex items-center justify-between w-full text-xs">
                        <div className="flex items-center">
                          <div className={`w-5 h-5 rounded-full flex items-center justify-center text-white text-xs font-medium mr-2 ${index < 3 ? 'bg-gradient-to-r from-blue-500 to-blue-600' : 'bg-gray-400'
                            }`}>
                            {index + 1}
                          </div>
                          <span className="font-medium">{item.province}</span>
                        </div>
                        <div className="flex items-center space-x-2">
                          <div className="text-center">
                            <div className="font-medium text-blue-600">{item.unique_users}</div>
                            <div className="text-gray-400 text-xs">用户</div>
                          </div>
                          <div className="text-center">
                            <div className="font-medium text-green-600">{item.user_conversion_rate}%</div>
                            <div className="text-gray-400 text-xs">转化</div>
                          </div>
                        </div>
                      </div>
                    </List.Item>
                  )}
                />

                {/* 异常IP提示 */}
                {Number(abnormalRate) > 5 && (
                  <div className="mt-2 p-2 bg-orange-50 border border-orange-200 rounded">
                    <div className="flex items-center text-orange-600 text-xs">
                      <WarningOutlined className="mr-1" />
                      <span className="font-medium">异常IP: {abnormalIPs}个 ({abnormalRate}%)</span>
                    </div>
                  </div>
                )}
              </Card>
            </Col>


          </Row>
        </Col>
        {/* DeepSeek状态 - 占满下半部分 */}
        <Col span={24}>
          <Card
            size="small"
            title={
              <div className="flex items-center justify-between">
                <div className="flex items-center space-x-2">
                  <RobotOutlined className="text-purple-500" style={{ fontSize: '14px' }} />
                  <span style={{ fontSize: '13px', fontWeight: 600 }}>DeepSeek AI服务</span>
                </div>
                {deepSeekInfo && (
                  <Badge
                    status={
                      deepSeekInfo.recommendations.overall_status === 'warning' ? "warning" :
                        deepSeekInfo.balance.status === 'sufficient' ? "success" : "error"
                    }
                    text={
                      deepSeekInfo.recommendations.overall_status === 'warning' ? "警告" :
                        deepSeekInfo.balance.status === 'sufficient' ? "正常" : "异常"
                    }
                  />
                )}
              </div>
            }
            style={{ height: '200px' }}
            bodyStyle={{ padding: '10px' }}
          >
            {deepSeekInfo ? (
              <Row gutter={[12, 8]}>
                <Col span={8}>
                  <div className="text-center p-2 bg-gradient-to-br from-green-50 to-emerald-50 rounded border border-green-100">
                    <div className="text-lg font-bold text-green-600">¥{deepSeekInfo.balance.total_balance_cny}</div>
                    <div className="text-xs text-gray-500">余额</div>
                    <div className="text-xs mt-1">
                      <span className={deepSeekInfo.balance.status === 'sufficient' ? "text-green-600" : "text-red-600"}>
                        {deepSeekInfo.balance.status === 'sufficient' ? '✅ 充足' : '⚠️ 不足'}
                      </span>
                    </div>
                  </div>
                </Col>

                <Col span={8}>
                  <div className="text-center p-2 bg-gradient-to-br from-blue-50 to-cyan-50 rounded border border-blue-100">
                    <div className="text-lg font-bold text-blue-600">{deepSeekInfo.usage.requests_month}</div>
                    <div className="text-xs text-gray-500">本月请求</div>
                    <div className="text-xs mt-1 text-gray-600">
                      ¥{deepSeekInfo.usage.efficiency.cost_per_request}/次
                    </div>
                  </div>
                </Col>

                <Col span={8}>
                  <div className="text-center p-2 bg-gradient-to-br from-purple-50 to-violet-50 rounded border border-purple-100">
                    <div className="text-lg font-bold text-purple-600">
                      {Object.values(deepSeekInfo.service.health_indicators).every(Boolean) ? '100' : '66'}
                    </div>
                    <div className="text-xs text-gray-500">健康评分</div>
                    <div className="text-xs mt-1">
                      <Progress
                        percent={Object.values(deepSeekInfo.service.health_indicators).every(Boolean) ? 100 : 66}
                        size="small"
                        strokeColor={Object.values(deepSeekInfo.service.health_indicators).every(Boolean) ? "#52c41a" : "#fa8c16"}
                        showInfo={false}
                      />
                    </div>
                  </div>
                </Col>

                {/* 提示信息 */}
                <Col span={24}>
                  {deepSeekInfo.recommendations.warnings.length > 0 && (
                    <div className="p-2 bg-orange-50 border border-orange-200 rounded">
                      <div className="text-orange-600 text-xs">
                        ⚠️ {deepSeekInfo.recommendations.warnings[0]}
                      </div>
                    </div>
                  )}

                  {deepSeekInfo.recommendations.tips.length > 0 && !deepSeekInfo.recommendations.warnings.length && (
                    <div className="p-2 bg-blue-50 border border-blue-200 rounded">
                      <div className="text-blue-600 text-xs">
                        💡 {deepSeekInfo.recommendations.tips[0]}
                      </div>
                    </div>
                  )}
                </Col>
              </Row>
            ) : (
              <div className="flex items-center justify-center h-full text-gray-400">
                <div className="text-center">
                  <RobotOutlined style={{ fontSize: '32px', marginBottom: '8px' }} />
                  <div className="text-sm">DeepSeek服务不可用</div>
                </div>
              </div>
            )}
          </Card>
        </Col>
      </Row>

      {/* 底部快速统计条 */}
      <div className="flex justify-between items-center text-xs text-gray-500 bg-gray-50 px-3 py-2 rounded">
        <span>产品: {appStats?.products?.total_products || 0} | 活跃: {appStats?.products?.active_products || 0}</span>
        <span>订单: {appStats?.orders?.total_orders || 0} | 今日: {appStats?.orders?.orders_today || 0}</span>
        <span>WebSocket: {appStats?.websocket?.totalConnections || 0} 连接</span>
        <span>
          DeepSeek: {deepSeekInfo ?
            `¥${deepSeekInfo.balance.total_balance_cny} | ${deepSeekInfo.usage.total_requests}次请求` :
            '离线'
          }
        </span>
        <span>更新: {serverInfo ? new Date(serverInfo.updateTime).toLocaleTimeString('zh-CN') : '--'}</span>
      </div>
    </div>
  );
};

export default Dashboard; 